/**
 * Created by tang on 2018/11/6.
 */
import { requestApi,requestUrl } from './global';
import { message } from 'antd';
import router from 'umi/router';
import axios from 'axios';
import qs from 'qs';
import Cookies from 'universal-cookie';
const cookie = new Cookies();

export default function request(url, options) {

  // 添加请求拦截器
  axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    if(cookie.get('token') && url !== '/web/user/login') {
      options.token = cookie.get('token')
      // options.token = 'eyJhbGciOiJIUzI1NiJ9.eyJ0aW1lIjoxNTY3MDQyNDM1NjcwLCJqdGkiOiIyYmE0ZjUyM2RjMmM0YjZjYWQyMDdlYjNkM2MyZTdhMCIsImlhdCI6MTU2NjE3ODQzNSwic3ViIjoiMzI0IiwiZXhwIjoxNTY3MDQyNDY1fQ.7Bo1bcijRvZnllwdMapHBG5efYujjQC7stePMgxhajc'
    }else if (!cookie.get('token')){
      router.push('/')
    }
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

   // 添加响应拦截器
   axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    if(response.data.recode !== 200 && response.data.recode !== 1001) {
      message.error(response.remsg)
    }

    if(response.data.recode === 1001) {
      cookie.remove('token')
      router.push('/')
    }
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });
  
  return axios({
    method: 'post',
    url: url,
    params: options,
    paramsSerializer: function(params) {
      return qs.stringify(params, {arrayFormat: 'repeat'})
    },
    baseURL: requestUrl+requestApi,
     // `headers` 是即将被发送的自定义请求头
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      "Access-Control-Allow-Credentials": true,
      "Access-Control-Allow-Origin": "*",
    },
    // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
    // 如果请求话费了超过 `timeout` 的时间，请求将被中断
    timeout: 10000,
  }).then(function (response) {
    return response.data
  })
}
